//
//  OrderViewController.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/11/1.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "OrderViewController.h"
#import "TopBackView.h"
#import "RLNetworkHelper.h"//网络判断
#import "WKProgressHUD.h"//提示框
//#import <MJRefresh.h>//下拉刷新
#import <MJRefresh/MJRefresh.h>
#import "NullView.h"
#import "Common.h"

#import "DriverOrderCell.h"
#import "RootViewController.h"
#import "LoginViewController.h"
//#import "DriverOrderDetailVC.h"
#import "OrderdetailVC.h"//订单详情
#import "PassageVC.h"//在途信息
#import "MyDriverVC.h"//指派司机
#import "DriverModel.h"

#define buttonW screenWidth/3

@interface OrderViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UIView *netView;

@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) NullView *nullView;
@property (nonatomic) int pageNo;
@property (nonatomic) NSInteger pageTotal;


@property (nonatomic,strong) NSMutableArray *buttonArr;
@property (nonatomic,strong) UILabel *redLabel;
@property (nonatomic) NSInteger integer;
@property (nonatomic) NSInteger currentInteger;


@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageNo = 1;
    self.pageTotal = 10;
    _integer = 0;
    _currentInteger = 0;
    self.dataArray = [NSMutableArray array];
    self.buttonArr = [NSMutableArray array];
    
    self.view.backgroundColor = WhiteColor;


    [self initTopView];
    [self initNullView];
    [self initTableView];

}

#pragma mark 初始化顶部view
-(void)initTopView
{
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"我的运单"];
    
    if ([self.hide isEqualToString:@"1"]) {
        topBackView.leftButton.hidden = NO;
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        
        
    } else {
        topBackView.leftButton.hidden = YES;
        
    }
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    

    
    [self.view addSubview:topBackView];

}

#pragma mark 没数据时网络提示页面
-(void)initNullView
{
    self.nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight) andTitle:@"" andImage:[UIImage imageNamed:@"no_order"]];
    self.nullView.backgroundColor = GrayColor;
    
    Common *c = [[Common alloc]init];
    //创建无网络状态view
    self.netView = [c noInternet:@"网络连接失败，请检查网络设备" and:self action:@selector(NoNetPressBtn) andCGreck:CGRectMake(0, 0, Main_Width, Main_height-64)];
}

-(void)initTableView
{
    [self initTopButton];
    
    if ([self.hide isEqualToString:@"1"]) {
        
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 65 + 35 * kHeight , screenWidth, screenHeight - 64 - 35 * kHeight) style:UITableViewStyleGrouped];
    } else {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 65 + 35 * kHeight, screenWidth, screenHeight - 64  - 48 * kHeight - 35 *kHeight) style:UITableViewStyleGrouped];
        
    }
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = GrayColor;
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    
    [self.view addSubview:self.tableView];

    //mj
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    
    //无网络状态
    [self createNetWorkAndStatue];
    
}

-(void)initTopButton
{
    
    self.redLabel = [[UILabel alloc]init];
    self.redLabel.backgroundColor = YellowColor;
    
    
    NSArray *arr = @[@"待派单",@"执行中",@"已完成"];
    
    for (int i = 0; i < arr.count; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i * buttonW, 64, buttonW, 35 * kHeight);
        [button setTitle:arr[i] forState:UIControlStateNormal];
        [button setTitleColor:carScrollColor forState:UIControlStateNormal];
        [button setTitleColor:YellowColor forState:UIControlStateSelected];
        button.titleLabel.font = Font(14);
        button.tag = i + 300;
        [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0) {
            button.selected = YES;
        }
        
        [self.view addSubview:button];
        
        [self.buttonArr addObject:button];
        
        self.redLabel.frame = CGRectMake(0, CGRectGetMaxY(button.frame), buttonW, 1);
        [self.view addSubview:self.redLabel];
        
    }
    
    
}

-(void)button:(UIButton *)sender
{
    
    self.pageNo = 1;
    _integer = sender.tag - 300;
    sender.selected = YES;
    for (UIButton *button in self.buttonArr) {
        if (button != sender) {
            button.selected = NO;
        }
    }
    
    
    CGFloat x = (sender.tag - 300 )*buttonW;
    [self.redLabel.layer addAnimation:[self moveX:0.3f X:[NSNumber numberWithFloat:x]] forKey:nil];
    
    [self initDataSource];
    
}

#pragma mark =====横向、纵向移动===========
-(CABasicAnimation *)moveX:(float)time X:(NSNumber *)x
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];///.y的话就向下移动。
    animation.toValue = x;
    animation.duration = time;
    animation.removedOnCompletion = NO;//yes的话，又返回原位置了。
    animation.repeatCount = 0;
    animation.fillMode = kCAFillModeForwards;
    return animation;
}


-(void)createNetWorkAndStatue{
    
    //判断是否有网
    [self judgeNetWork];
    //创建加载状态
}

//判断是否有网
-(void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        [self.tableView addSubview:self.netView];
        self.hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
        
    }
    else{
        [self.netView removeFromSuperview];
        [self initDataSource];
    }
}
//无网络状态
-(void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        [self.netView removeFromSuperview];
        [self initDataSource];
    } else {
        [self.hud dismiss:YES];
    }
}

-(void)downRefresh{
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    self.pageNo = 1;
    
    [self judgeNetWork];
}
-(void)upRefresh{
    
    if (self.pageNo != (int)self.pageTotal) {
        self.pageNo ++;
        [self judgeNetWork];
        [self.tableView.mj_footer endRefreshing];
    }else{
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView.mj_header endRefreshing];
}

#pragma mark 网络数据
-(void)initDataSource
{
    /*
     //假数据
     NSDictionary *dic = [NSDictionary dictionary];
     
     NSString *path = [[NSBundle mainBundle]pathForResource:@"dingdan" ofType:@"txt"];
     
     
     NSString *conters = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
     NSData *data = [conters dataUsingEncoding:NSUTF8StringEncoding];
     dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
     
     
     for (NSDictionary *diction in dic[@"data"]) {
     DriverModel *model = [[DriverModel alloc]init];
     
     [model setValuesForKeysWithDictionary:diction];
     
     
     [self.dataArray addObject:model];
     
     }
    
    
    if (self.dataArray.count > 0) {
        [self.nullView removeFromSuperview];
    } else {
        [self.tableView addSubview:self.nullView];
    }

    [self.tableView reloadData];
*/
    
    
    
    NSString *string;
    if (_integer == 0) {
        string = mission_waiting ;
        self.nullView.label.text = @"暂无待接单订单";
        
    } else if (_integer == 1) {
            string = mission_execution ;
            self.nullView.label.text = @"暂无执行中订单";
    }  else if(_integer == 2){
            string = mission_done;
            self.nullView.label.text = @"暂无已完成订单";
            
    }


    NSString *urlString = [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=%@",string,self.pageNo,@"10"];
    
    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss: YES];
        
        if (self.dataArray.count > 0 && self.pageNo == 1) {
            
            [self.dataArray removeAllObjects];
            
        }
        
        self.pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];
        
        
        if ([responseObj[@"success"] boolValue]) {
            
            [self.hud dismiss:YES];
            
            if ([responseObj[@"data"][@"list"] isEqual:[NSNull null]]) {
                
            } else {
            
            
            for (NSDictionary *dic in responseObj[@"data"][@"list"]) {
                DriverModel *model = [[DriverModel alloc]init];
                
                [model setValuesForKeysWithDictionary:dic];
                
                [self.dataArray addObject:model];
                
            }
            }
            
            if (self.dataArray.count > 0) {
                [self.nullView removeFromSuperview];
            } else {
                [self.tableView addSubview:self.nullView];
            }
            
            [self.tableView reloadData];

        } else {
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];

        }
        
        

        
    } failed:^(NSString *errorMsg) {
        [self.hud dismiss:YES];
        NSLog(@"%@",errorMsg);
    }];

}


#pragma mark UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = @"driverOrderCell";
   
    DriverOrderCell  *cell = [[DriverOrderCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    
    if (self.dataArray.count > 0) {
        
        cell.number = _integer;
        cell.model = self.dataArray[indexPath.section];

    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    
    //详情
    [cell.detailButton addTarget:self action:@selector(detailButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.detailButton.tag = indexPath.section + 500;
    
    //在途信息
    [cell.giveButton addTarget:self
                        action:@selector(wayAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.giveButton.tag = indexPath.section + 1000;
    
    //指派司机
    [cell.assignButton addTarget:self
                        action:@selector(assignDriver:) forControlEvents:UIControlEventTouchUpInside];
    cell.assignButton.tag = indexPath.section + 1500;

    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5 * kHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90 * kHeight + 73;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    OrderdetailVC *detailVC = [[OrderdetailVC alloc]init];
    
    DriverModel *model = [[DriverModel alloc]init];
    model = self.dataArray[indexPath.section];
    
    detailVC.orderID = model.ID;
    detailVC.number = _integer;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}
#pragma mark 查看详情
-(void)detailButton:(UIButton *)sender
{
    OrderdetailVC *detailVC = [[OrderdetailVC alloc]init];
    
    DriverModel *model = [[DriverModel alloc]init];
    model = self.dataArray[sender.tag - 500];
    
    detailVC.orderID = model.ID;
    
    detailVC.number = _integer;

    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark 指派司机
-(void)assignDriver:(UIButton *)sender
{
    MyDriverVC *driverVC = [[MyDriverVC alloc]init];
    DriverModel *model = [[DriverModel alloc]init];
    model = self.dataArray[sender.tag - 1500];
    driverVC.orderId = model.ID;
    [self.navigationController pushViewController:driverVC animated:YES];
    
}

#pragma mark 在途信息
-(void)wayAction:(UIButton *)sender
{
    PassageVC *passageV = [[PassageVC alloc]init];
    DriverModel *model = [[DriverModel alloc]init];
    model = self.dataArray[sender.tag - 1000];
    passageV.orderId = model.ID;
    passageV.orderNumber = model.orderCode;
    [self.navigationController pushViewController:passageV animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{

    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    if ([self.hide isEqualToString:@"1"]) {
        
        [rootVC setTabBarHidden:YES];
        
    } else {
        
        [rootVC setTabBarHidden:NO];
        
    }
    
    [self initDataSource];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    if ([rootVC.rootString isEqualToString:@"1"]) {
        
        [self present];
        
        rootVC.rootString = @"2";
        
    }
    
    if ([self.hide isEqualToString:@"1"]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        
    } else {
        
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        
    }
    
}

-(void)present
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [userDefaults objectForKey:@"login"];
    
    if (string == nil ) {
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        loginVC.topBackView.leftButton.hidden = YES;
        UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        loginVC.backToFirst = @"1";
        
        [self presentViewController:loginNC animated:YES completion:nil];
        
    }
    
}


//如果从个人中心进入 返回上一级
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
